<?php

namespace Contact;

use Application\ModelAbstract;

class Model extends ModelAbstract
{
    protected $table;

    public function __construct()
    {
        $this->table = 'contact';
        parent::__construct();
    }

    public function insert($data)
    {
        $service = $data['service'];
        unset($data['service']);
        $data['submitted'] = date('Y-m-d H:i:s', time());
        $select = $this->getDb()->select();
        $select->from('service', 'id');
        $select->where('id in (?)', $service);
        $service = $this->getDb()->fetchAll($select);
        $this->getDb()->beginTransaction();
        $this->getDb()->insert($this->table, $data);
        $contactId = $this->getDb()->lastInsertId();
        foreach ($service as $value) {
            if (!$this->getDb()->insert('contactService', ['contactId' => $contactId, 'serviceId' => $value['id']])) {
                $this->getDb()->rollBack();
            }
        }
        $this->getDb()->commit();
        return $this;
    }

    public function getServiceList()
    {
        $select = $this->getDb()->select();
        $select->from('service', ['id', 'title']);
        $select->order('sorter');
        return $this->getDb()->fetchPairs($select);
    }

    public function getService($id)
    {
        $select = $this->getDb()->select();
        $select->from('contactService', '');
        $select->join('service', 'contactService.serviceId = service.id', 'service.title');
        $select->where('contactId = ?', $id);
        return $this->getDb()->fetchCol($select);
    }

    public function search($search, $order, $desc = null)
    {
        $select = $this->getDb()->select();
        $select->from($this->table);
        if ($search['serviceId']) {
            $select->join('contactService', 'contactService.contactId = contact.id', '');
            $select->where('serviceId = ?', $search['serviceId']);
        }
        if ($search['q']) {
            $query = str_replace(array('\\', '_', '%'), array('\\\\', '\_', '\%'), $search['q']);
            $select->where('comments LIKE ?', '%' . $query . '%');
        }
        if ($order) {
            if (null !== $desc) {
                $order .= ' DESC';
            }
            $select->order($order);
        }
        return $select->query()->fetchAll();
    }
}

/*
Services
[X] IPTV
[x] Internet
[x] Mail
[x] Cable TV

tbl_Service
id | title | sorter
1  | IPTV  | 0

tbl_Contact
tbl_ContactService (contactId, serviceId)

FOREIGN KEY

Admin End.

Search [____________________] Service [All   ] [ Search ] [ Reset ]

list ...

 */